﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MetroFramework.Forms;
using System.Runtime.InteropServices;
using MetroFramework;
using System.Configuration;

// http://blog.csdn.net/linux7985/article/details/39554081

namespace TranslateApp{
    public partial class MiniForm : MetroForm{
        public MiniForm(){
            InitializeComponent();
            #region debug

                #if(DEBUG)
                    this.ShowInTaskbar = true;
                #endif

            #endregion
        }

        private void MiniForm_Load(object sender, EventArgs e){
            var apikey = ConfigurationManager.AppSettings["APIKEY"];
            Baidu.API.Config.Init(apikey);
            var locationX = ConfigurationManager.AppSettings["Location.x"];
            var locationY = ConfigurationManager.AppSettings["Location.y"];

            this.Location = new Point(int.Parse(locationX), int.Parse(locationY));

            // 安装钩子
            _kHook = new Hook.KeyboardHook();
            _kHook.KeyUp += _kHook_KeyUp;
            _kHook.Install();

            _bkWorker = new BackgroundWorker();
            _bkWorker.DoWork += _bkWorker_DoWork;

            _bkQuery = new BackgroundWorker();
            _bkQuery.DoWork += _bkQuery_DoWork;
        }

        private void MiniForm_FormClosed(object sender, FormClosedEventArgs e){
            _kHook.Uninstall();

            var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["Location.x"].Value = this.Location.X.ToString();
            config.AppSettings.Settings["Location.y"].Value = this.Location.Y.ToString();
            config.Save();

        }

        private void mBtnTrans_Click(object sender, EventArgs e){
            _bkQuery.RunWorkerAsync();
        }

        private void _bkQuery_DoWork(object sender, DoWorkEventArgs e){
            var words = string.Empty;
            this.Invoke(new MethodInvoker(() => {
                words = mTxtInput.Text.Trim();
            }));
            var dicResult = Baidu.API.Dictionary.AutoQuery(words);
            var result = string.Empty;
            if (dicResult.IsSuccess()){
                result = dicResult.ToString();
            }
            else{
                var tranResult = Baidu.API.Translate.Trans(words);
                result = tranResult.ToString();
            }

            lock (_threadLock){
                this.Invoke(new MethodInvoker(() => {
                    mTxtContent.Text = result;
                }));
            }
        }

        #region 键盘钩子处理
        /// <summary>
        /// 键盘钩子的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _kHook_KeyUp(object sender, Hook.HookEventArgs e) {
            if (e.Key == Keys.LControlKey) {
                // Debug.WriteLine(@"LControlKey KeyUp.");
                if (_workState == WorkerKeyState.FirstPress) {
                    _workState = WorkerKeyState.SecondPress;
                }
                if (_workState == WorkerKeyState.None) {
                    var startTime = DateTime.Now.Ticks;
                    _bkWorker.RunWorkerAsync(startTime);
                    Debug.WriteLine(@"worker start at {0}.", DateTime.Now);
                }

            }
        }

        /// <summary>
        /// 后台线程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _bkWorker_DoWork(object sender, DoWorkEventArgs e) {
            _workState = WorkerKeyState.FirstPress;
            var startTime = (long)e.Argument;
            while (DateTime.Now.Ticks - startTime < WaitTimeTicks) {
                if (_workState == WorkerKeyState.SecondPress) {
                    lock (_threadLock) {
                        Debug.WriteLine(@"double ctrl.");
                        this.Invoke(new MethodInvoker(() => {
                            if (this.Visible) {
                                this.Hide();
                            }
                            else {
                                this.Show();
                            }
                        }));
                    }
                    break;
                }
                // 加上这个可以降低CPU占用
                System.Threading.Thread.Sleep(10);
            }

            _workState = WorkerKeyState.None;
            Debug.WriteLine(@"worker out.");
        }
        #endregion

        #region WordsIScn 判断句子中是否含有中文
        /// <summary>
        /// 判断句子中是否含有中文     宁夏大学 张冬 zd4004.blog.163.com
        /// </summary>
        /// <param name="words"></param>
        /// <returns></returns>
        private static bool WordsIScn(string words) {
            string TmmP;

            for (int i = 0; i < words.Length; i++) {
                TmmP = words.Substring(i, 1);

                byte[] sarr = System.Text.Encoding.GetEncoding("gb2312").GetBytes(TmmP);

                if (sarr.Length == 2) {
                    return true;
                }
            }
            return false;
        } 
        #endregion

        /// <summary>
        /// 线程按键状态
        /// </summary>
        private enum WorkerKeyState{
            None,
            FirstPress,
            SecondPress
        }

        /// <summary>
        /// 键盘HOOK对象
        /// </summary>
        private Hook.KeyboardHook _kHook;

        private BackgroundWorker _bkQuery;
        private object _threadLock = new object();
        private WorkerKeyState _workState = WorkerKeyState.None;
        private BackgroundWorker _bkWorker;
        private const long WaitTimeTicks = 5000 * 1000; // 5000毫秒

    }


}
